<script setup>
	import {
		ref,
		onMounted
	} from "vue"
	import {
		onShow,
	} from '@dcloudio/uni-app'

	let props = defineProps({
		'height': {
			type: String,
			default: '300rpx'
		},
		'getDataF': null, // 获取数据的函数
		'dataAttr': { // 接口返回数据的字段
			type: String,
			default: 'data'
		}
	})

	let listData = ref([])
	let pageNum = ref(1)
	let pageSize = ref(10)
	let moreStatus = ref('more')
	const triggered = ref(false)
	const onRefresh = async () => {
		triggered.value = true;

		await reset()
		
		triggered.value = false;
	}
	
	const getValue = (obj, key) => {
		if (typeof key !== 'string') return
		
		return key.split('.').reduce((pre, cur) => pre[cur] || [], obj)
	}

	let getData = async () => {
		moreStatus.value = 'loading'
		await props.getDataF(pageNum.value, pageSize.value).then(res => {
			const data = getValue(res, props.dataAttr)
			if (data.length > 0) {
				listData.value.push(...data)
				moreStatus.value = 'more'
			} else {
				moreStatus.value = 'noMore'
			}
		})
		pageNum.value++
	}

	let lower = () => {
		getData()
	}

	const reset = async () => {
		listData.value = []
		pageNum.value = 1
		await getData()
	}

	onMounted(() => {
		getData()
	})

	// onShow(() => {
	// 	reset()
	// })

	defineExpose({
		reset
	})
</script>

<template>
	<scroll-view :style="{ height: height }" scroll-y="true" refresher-enabled :refresher-triggered="triggered"
		@refresherrefresh="onRefresh" @scrolltolower="lower">
		<slot :listData="listData"></slot>
		<uni-load-more :status="moreStatus" :showIcon="false" @clickLoadMore="getData" />
	</scroll-view>
</template>

<style scoped>
</style>